# encoding: utf-8
# @author: wangxin
# @software: garner
# @file: setmealDetailViews.py
# @time: 2025/2/14 15:31
import json

from django.core import serializers
from django.db.models import Q
from django.http import HttpResponse, JsonResponse
from django.views import View
import  pymysql
from app.models import TSetmeal, TSetmealCheckgroup


class setmealDetail(View):
    '''
    参数:
    - request: HttpRequest对象，封装了用户的请求信息。
    - setmeal_id: int，数据库中套餐的唯一标识符。
    '''
    def get(self, request,setmeal_id):
        dataTable = dict()
        # 根据套餐ID获取特定的套餐对象
        setMeal=TSetmeal.objects.get(setmeal_id=setmeal_id)
        dataTable["img"] = setMeal.img
        dataTable["name"] = setMeal.name
        dataTable["sex"] = setMeal.sex
        dataTable["age"] = setMeal.age
        dataTable["id"] = setMeal.setmeal_id
        conn = pymysql.Connect(
            host="127.0.0.1",
            port=3306, user="root",
            password="123456",
            db="ruici",
            charset="utf8",
            autocommit=True
        )

        cursor = conn.cursor()
        sql = f"SELECT  checkgroup_id FROM t_setmeal_checkgroup WHERE setmeal_id ={setmeal_id}"
        cursor.execute(sql)
        res=cursor.fetchall()

        checkgroup_list = []

        for item in res:
            checkgrouo_id=item[0]
            sql2 = f"SELECT * FROM t_checkgroup WHERE id ={checkgrouo_id}"
            cursor.execute(sql2)
            res2=cursor.fetchone()

            checkgroup_dict = dict()
            checkgroup_dict['name']=res2[2]
            checkgroup_dict['remark'] = res2[5]

            sql3=f"SELECT * FROM t_checkitem WHERE id in (SELECT checkitem_id FROM t_checkgroup_checkitem WHERE checkgroup_id = {checkgrouo_id});"
            cursor.execute(sql3)
            res3 = cursor.fetchall()
            checkitem_names=[]
            checkitem_names_str=str()
            for item in res3:
                checkitem_names.append(str(item[2]))
                # 使用join()方法将列表中的元素连接成一个字符串，元素之间用逗号分隔
                checkitem_names_str = ','.join(checkitem_names)

            checkgroup_dict['checkitem_names']=checkitem_names_str
            checkgroup_list.append(checkgroup_dict)
        dataTable["checkgroup"] = checkgroup_list
        print(dataTable)



        result = {
            "status": "200",
            "message": "获取套餐详情成功",
            "data": dataTable,
        }

        return JsonResponse(result)



